package com.atguigu.daijia.customer.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.customer.mapper.CustomerInfoMapper;
import com.atguigu.daijia.customer.mapper.CustomerLoginLogMapper;
import com.atguigu.daijia.customer.service.CustomerInfoService;
import com.atguigu.daijia.model.entity.customer.CustomerInfo;
import com.atguigu.daijia.model.entity.customer.CustomerLoginLog;
import com.atguigu.daijia.model.form.customer.UpdateWxPhoneForm;
import com.atguigu.daijia.model.vo.customer.CustomerLoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
@RequiredArgsConstructor
public class CustomerInfoServiceImpl extends ServiceImpl<CustomerInfoMapper, CustomerInfo> implements CustomerInfoService {

    private final WxMaService wxMaService;
    private final CustomerLoginLogMapper customerLoginLogMapper;

    /**
     * 微信小程序登录接口
     * @param code
     * @return
     */
    @Override
    @Transactional
    public Long login(String code) {
        // 1 使用微信 Java SDK 使用临时登录凭证 code 获取微信用户唯一标识 openId
        String openid = null;
        try {
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            openid = sessionInfo.getOpenid();
        } catch (WxErrorException e) {
            e.printStackTrace();
            // 登录失败，抛出自定义异常，后续代码不会执行
            throw new GuiguException(ResultCodeEnum.WX_CODE_ERROR);
        }

        // 2 根据 openId 查询数据库，如果存在，直接返回用户id，不存在，创建用户，返回用户id
        CustomerInfo customerInfo = this.getOne(new LambdaQueryWrapper<CustomerInfo>().eq(CustomerInfo::getWxOpenId, openid));
        if (customerInfo == null) {
            customerInfo = new CustomerInfo();
            customerInfo.setWxOpenId(openid);
            customerInfo.setNickname(String.valueOf(System.currentTimeMillis()));
            // 默认头像
            customerInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            this.save(customerInfo);
        }
        // 3 记录登录日志
        CustomerLoginLog customerLoginLog = new CustomerLoginLog();
        customerLoginLog.setCustomerId(customerInfo.getId());
        customerLoginLog.setMsg("小程序登录成功");
        customerLoginLogMapper.insert(customerLoginLog);
        return customerInfo.getId();
    }

    /**
     * 根据用户 ID 获取用户基本信息
     * @param customerId
     * @return
     */
    @Override
    public CustomerLoginVo getCustomerLoginInfo(Long customerId) {
        CustomerInfo customerInfo = this.getById(customerId);
        if (customerInfo != null) {
            CustomerLoginVo customerLoginVo = new CustomerLoginVo();
            BeanUtils.copyProperties(customerInfo, customerLoginVo);
            // 判断是否绑定手机号码，如果未绑定，用户小程序端会发起绑定事件
            customerLoginVo.setIsBindPhone(StringUtils.hasText(customerInfo.getPhone()));
            return customerLoginVo;
        }
        return null;
    }

    /**
     * 绑定用户手机号
     * @param updateWxPhoneForm
     * @return
     */
    @Override
    public Boolean updateWxPhoneNumber(UpdateWxPhoneForm updateWxPhoneForm) {
        // 调用微信 Java SDK，获取当前用户的手机号
        WxMaPhoneNumberInfo phoneNoInfo = null;
        try {
            phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(updateWxPhoneForm.getCode());
        } catch (WxErrorException e) {
            e.printStackTrace();
            // 登录失败，抛出自定义异常，后续代码不会执行
            throw new GuiguException(ResultCodeEnum.WX_CODE_ERROR);
        }

        String phoneNumber = phoneNoInfo.getPhoneNumber();
        CustomerInfo customerInfo = new CustomerInfo();
        customerInfo.setId(updateWxPhoneForm.getCustomerId());
        customerInfo.setPhone(phoneNumber);

        return this.updateById(customerInfo);
    }

    /**
     * 获取乘客 OpenId
     * @param customerId
     * @return
     */
    @Override
    public String getCustomerOpenId(Long customerId) {
        CustomerInfo customerInfo = this.getOne(new LambdaQueryWrapper<CustomerInfo>().eq(CustomerInfo::getId, customerId).select(CustomerInfo::getWxOpenId));
        return customerInfo.getWxOpenId();
    }
}
